package conlon.rocketmq.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


/**
 * @Author conlon
 * @Description 消息发送者
 * @Date 2021/1/6 20:37
 **/
@Component
@Slf4j
public class RocketMqProducer {


    @Value("${rocketmq.namesrvAddr:}")
    private String nameSrvAddr;

    @Value("${rocketmq.default.groupName:}")
    private String defaultGroupName;

    @Value("${rocketmq.transaction.groupName:}")
    private String transactionGroupName;


    @Bean(value = "defaultMqProducer")
    public DefaultMQProducer getRocketMqProducer() {
        DefaultMQProducer defaultMqProducer = new DefaultMQProducer(defaultGroupName);
        defaultMqProducer.setNamesrvAddr(nameSrvAddr);
        defaultMqProducer.setVipChannelEnabled(false);
        try {
            defaultMqProducer.start();
        } catch (MQClientException e) {
            log.error("RocketMqProducer-MQClientException : ", e);
        }
        return defaultMqProducer;
    }

    /**
     * TransactionStatus.CommitTransaction: 提交事务，它允许消费者消费此消息。
     * TransactionStatus.RollbackTransaction: 回滚事务，它代表该消息将被删除，不允许被消费。
     * TransactionStatus.Unknown: 中间状态，它代表需要检查消息队列来确定状态。
     **/
    @Bean(value = "transactionMqProducer")
    public TransactionMQProducer getTransactionMqProducer() {
        TransactionMQProducer transactionMqProducer = new TransactionMQProducer(transactionGroupName);
        transactionMqProducer.setNamesrvAddr(nameSrvAddr);
        transactionMqProducer.setVipChannelEnabled(false);
        try {
            transactionMqProducer.start();
        } catch (MQClientException e) {
            log.error("RocketMqProducer-MQClientException : ", e);
        }
        return transactionMqProducer;
    }

}

